package com.addressbook.tests;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.testng.annotations.Test;

import com.addressbook.fw.GroupData;
import com.addressbook.utils.SortedListOf;

public class GroupDeletionTests extends TestBase {

	private SortedListOf<Integer> randomIndexesToDelete(int GroupListSize) {
		Random rnd = new Random();
		if (GroupListSize == 0)
			throw new Error("There is no groups to Delete.");
		int size = rnd.nextInt(GroupListSize);
		SortedListOf<Integer> index = new SortedListOf<Integer>();
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < GroupListSize; i++)
			list.add(i);
		for (int i = 0; i < size; i++) {
			int j = rnd.nextInt(list.size());
			index.add(list.get(j));
			list.remove(j);
		}
		return index;
	}

	@Test
	public void testGroupDeletion() {

		// save old
		SortedListOf<GroupData> oldstate =  new SortedListOf<GroupData> (app.getHibernateHelper().listGroups());

		SortedListOf<Integer> index = randomIndexesToDelete(oldstate.size());

		app.getGroupHelper().deleteGroup(index);

		// save new
		SortedListOf<GroupData> newstate = app.getGroupHelper().getGroupsName();

		// check
		assertThat(newstate, equalTo(oldstate.without(index)));
	}
}
